/************************************************************************
 * The code is owned by mainframer.cn and Shang Tao
 * Without aproval of mainframer.cn and Shang Tao, removing the copyright
 * infomation is regarded as invassion of proprietary copyright
 ***********************************************************************/
package com.mr.qa.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.hibernate.Transaction;

import com.mr.qa.UserSession;
import com.mr.qa.UserSessionUtil;
import com.mr.qa.bo.QuestionCategory;
import com.mr.qa.dao.impl.QuestionCategoryDAO;
import com.mr.qa.exception.QaException;
import com.mr.qa.form.TrainingApplicationForm;
import com.mr.qa.util.HibernateSessionFactory;
import com.mr.qa.util.mail.Mail;
import com.mr.qa.util.mail.MailUtil;

public class TrainingApplicationAction extends BaseAction {

    private static final Log log = LogFactory.getLog(TrainingApplicationAction.class);
    public TrainingApplicationAction() {
    }
    public ActionForward doAction(ActionMapping mapping, ActionForm form,
                        HttpServletRequest request, HttpServletResponse response) throws QaException
    {
        ActionForward af = null;
        TrainingApplicationForm appForm = (TrainingApplicationForm)form;
        ActionMessages errors = new ActionMessages();
        ActionMessages messages = new ActionMessages();
//        UserSession us = null;
        String errorCode = "0"; 
        String trainingId = "";
        UserSession us = UserSessionUtil.getUserSession(request);
        String action = "success";
        try 
        {
			// same as question id
			trainingId = appForm.getTrainingId();
			if (trainingId == null) {
				log.error("no trainingId provided");
				errorCode = "1";
				throw new QaException("no trainingId provided");
			}

			if (us == null) {
				String originalUrl = "/question.mrqa?action=view&id=" + appForm.getTrainingId();
				request.setAttribute(this.ORIGINAL_URL_NAME, originalUrl);
				action = "addanswerconfirmforanonymoususer";
			} else {
				// same as question category id
				String trainingCategoryId = appForm.getTrainingCategoryId();

				QuestionCategory category = this.getQuestionCategory(trainingCategoryId);
				if (category == null) {
					log.error("no question category by trainingCategoryId:"	+ trainingCategoryId);
					errorCode = "2";
					throw new QaException("no question category by trainingCategoryId:"	+ trainingCategoryId);
				}
				String receiverMail = category.getAdCategoryContactMail();
				if (receiverMail == null) {
					log.error("no specified mail for trainingCategory " + trainingCategoryId + ":" + category.getName());
					errorCode = "3";
					throw new QaException("no specified mail for trainingCategory " + trainingCategoryId + ":" + category.getName());
				}
				String trainingName = appForm.getTrainingName();// Literal
				String trainingNameLiteral = appForm.getTrainingNameLiteral();

				String loginName = appForm.getLoginName();
				String loginNameLiteral = appForm.getLoginNameLiteral();

				String name = appForm.getName();
				String nameLiteral = appForm.getNameLiteral();

				String sex = appForm.getSex();
				String sexLiteral = appForm.getSexLiteral();

				String hp = appForm.getHp();
				String hpLiteral = appForm.getHpLiteral();

				String email = appForm.getEmail();
				String emailLiteral = appForm.getEmailLiteral();

				String company = appForm.getCompany();
				String companyLiteral = appForm.getCompanyLiteral();

				String concerns = appForm.getConcerns();
				String concernsLiteral = appForm.getConcernsLiteral();

				String emailTitle = name + appForm.getText1() + appForm.getText3() + ":" + trainingName + appForm.getText2() + " www.mainframer.cn/iask";
				String emailBody = appForm.getText1() + appForm.getText3() + ":" + trainingName + "<br>";
				emailBody += loginNameLiteral + ":" + loginName + "<br>";
				emailBody += nameLiteral + ":" + name + "<br>";
				sex = ("M".equals(sex)) ? appForm.getText5() : appForm.getText6();
				emailBody += sexLiteral + ":" + sex + "<br>";
				emailBody += hpLiteral + ":" + hp + "<br>";
				emailBody += emailLiteral + ":" + email + "<br>";
				emailBody += companyLiteral + ":" + company + "<br>";
				emailBody += concernsLiteral + ":<pre>" + concerns
						+ "</pre><br><br>";
				emailBody += appForm.getText4() + ":http://www.mainframer.cn" + request.getContextPath()
						+ "/question.mrqa?ation=view&id=" + trainingId + "<br>";
				emailBody += appForm.getText2() + ":" + "http://www.mainframer.cn/iask" + "<br>";
				boolean sendMail = sendTrainingApplicationAsMail(emailTitle, emailBody, receiverMail);
				if (!sendMail) {
					errors.add("", new ActionMessage("sendtrainingmail.failure"));
				} else {
					messages.add("", new ActionMessage("sendtrainingmail.success"));
				}
			}
		}
        catch(QaException qe) {
            errors.add("", new ActionMessage("sendtrainingmail.failure"));
        }
        catch(Exception e) {
            errors.add("", new ActionMessage("sendtrainingmail.failure"));
        }
        if(errors.size() > 0)
        saveErrors(request.getSession(), errors);
        if(messages.size() > 0)
        saveMessages(request.getSession(), messages);
        String path = mapping.findForward(action).getPath();
        path = path.replace("!?",""+trainingId);
        af = new ActionForward(path);
        af.setRedirect(true);
        return af;
    }

    private boolean sendTrainingApplicationAsMail(String mailTitle,String mailBody,String toMail)
    {
        boolean sendOk = true;
        try
        {
            Mail htmlMail = new Mail();
            htmlMail.setFrom("service@mainframer.cn");
            htmlMail.setTo(toMail);
            htmlMail.setSubject(mailTitle);
            htmlMail.setBody(mailBody);
            MailUtil.sendServiceSimpleHtmlMail(htmlMail);
            log.info("send mail:"+mailTitle+" to "+toMail);
        }
        catch(QaException qe)
        {
            sendOk = false;
            log.error("send training mail QaException:"+qe);
        }
        catch(Exception e)
        {
            sendOk = false;
            log.error("send training mail Exception:"+e);
        }
        return sendOk;
    }

        private QuestionCategory getQuestionCategory(String questionCategoryId)
        {
            Transaction tx = null;
            try
            {
                QuestionCategoryDAO categoryDAO = new QuestionCategoryDAO();
                tx = HibernateSessionFactory.getSession().beginTransaction();
                QuestionCategory category = categoryDAO.findById(new Integer(questionCategoryId));
                tx.commit();
                return category;
            }
            catch(Exception e)
            {
                log.warn("find category by id="+questionCategoryId);
            }
            finally
            {
                HibernateSessionFactory.closeSession();  
            }
            return null;
        }

}
